﻿/// <reference path="~/Scripts/Library/jquery-1.9.1.min.js" />

var selectedObjectType = "";

var selectedController = "";

var selectedAction = "";

var selectedParameters = "";

var isWindowResizing = false;


var ContentGrid_ColumnModels = new Array();

ContentGrid_ColumnModels["Sponsor"] =

        [

            { name: "Id", width: 80, fixed: true, sortable: false, hidden: true },

            { name: "Name" },

            { name: "NationalEmployerd", label: "National Employer Id", width: 100, fixed: true, align: "center" },

            { name: "UniqueId", label: "Unique Id", width: 100, fixed: true, align: "center" },

            { name: "FederalTaxId", label: "Tax Id", width: 100, fixed: true, align: "center" },

            { name: "Action", label: "Action", width: 40, fixed: true, search: false, sortable: false, align: "center", formatter: ContentGrid_Formatter_Action_Sponsor }

        ];

ContentGrid_ColumnModels["SponsorType"] =

        [

            { name: "Id", width: 80, fixed: true, sortable: false, hidden: true },

            { name: "Name" },

            { name: "Enabled", label: "Enabled", width: 60, fixed: true, align: "center" },

            { name: "Action", label: "Action", width: 40, fixed: true, search: false, sortable: false, align: "center", formatter: ContentGrid_Formatter_Action }

        ];


function TopLevelSelection_OnClick(sender) {

    $("td.ContentSelectionContainer").show(); // RE-SHOW THE MIDDLE COLUMN, THIS IS HIDDEN DURING SEARCH RESULTS

    $(".ContentSelection").hide(); // HIDE ALL PREVIOUS CONTENT SELECTIONS 

    $("#ContentHeader").hide(); // HIDE CONTENT HEADER 

    $("#ContentBody").hide(); // CLEAR CONTENT WINDOW

    // SHOW THE CLICK CONTENT SELECTION 

    if (sender != undefined) {

        $("#" + sender.id + "Selection").show();

        $("td.ContentSelectionContainer").addClass("ContentSelectionContainerInactive");

    }

    Window_OnResize();

}

function ContentSelection_OnClick(sender) {

    $(".ContentSelection").hide(); // HIDE ALL PREVIOUS CONTENT SELECTIONS 

    $(sender).closest("div").show(); // SHOW PARENT SELECTION TO MAKE SURE THE LINK IS NOT BROKE

    $("td.ContentSelectionContainer").addClass("ContentSelectionContainerInactive");


    selectedObjectType = $(sender).attr("objectType");

    selectedController = $(sender).attr("controller");

    selectedAction = $(sender).attr("action");

    selectedParameters = $(sender).attr("parameters");

    if ((selectedObjectType != "") && (selectedObjectType != undefined)) {

        $("#ContentHeader").show();

        $("#ContentHeader").text(sender.innerHTML);

        $("#ContentBody").show();

        Window_OnResize();

        ContentGrid_Refresh();

    }

    else {

        $("#ContentHeader").hide(); // HIDE CONTENT HEADER 

        $("#ContentBody").hide(); // CLEAR CONTENT WINDOW

    }

    Window_OnResize();

    return;

}

function CloseAllSelections_OnClick(sender) {

    $(".ContentSelection").hide(); // HIDE ALL PREVIOUS CONTENT SELECTIONS 

    $("#ContentBody").hide(); // CLEAR CONTENT WINDOW

    $("#ContentHeader").hide(); // HIDE CONTENT HEADER 

    $("td.ContentSelectionContainer").removeClass("ContentSelectionContainerInactive");

    Window_OnResize();

}

function Window_OnResize() {

    if (isWindowResizing) { return; }

    isWindowResizing = true;


    var availableHeight = Application.Window.Height();

    availableHeight -= $("#SponsorContent").offset().top * 2; // REMOVE MARGIN HEIGHT

    availableHeight += 8; // ADD BACK BORDER HEIGHT

    if (availableHeight < 400) { availableHeight = 400; } // MAKE SURE MINIMUM SIZE

    $("#SponsorContent").height(availableHeight);

    $("td.Content").height(availableHeight);

    availableHeight -= $("#ContentHeader:visible").outerHeight();

    $("#ContentBody").height(availableHeight);


    $("#ContentGrid").setGridWidth(1); // SHRINK GRID SO THAT THE COLUMN CAN BE SIZED 

    // RESIZE CONTENT COLUMNS TO REFIT GRID

    $("td.ContentRootSelectionContainer").width(220);

    $("td.ContentSelectionContainer").width(200);

    $("td.Content").css("width", "");


    // RESIZE GRID ON SEPARATE THREAD (TO ALLOW REDRAW TO FINISH)

    setTimeout(function () { jqGrid_ResizeToFit("ContentGrid"); }, 1);


    isWindowResizing = false;

}


function ContentGrid_Formatter_Action(cellValue, options, rowObject) {

    var formattedCellValue = "";

    var iconEdit = "<span class=\"ui-icon ui-icon-pencil\"></span>";

    var iconDelete = "<span class=\"ui-icon ui-icon-trash\"></span>";

    // USE THE SELECTED OBJECT TYPE VERSUS THE INCOMING OBJECT TYPE

    // THIS IS TO SUPPORT WHEN ONE OBJECT TYPE IS USED BY SEPARATE CONFIG OPTIONS (E.G. ROLE COULD BE ENTERPRISE OR ENVIRONMENT)

    var href = $("#RootUrl").val() + selectedController + "/" + selectedObjectType + "/" + rowObject.Id;

    var target = rowObject.ObjectType + "_" + rowObject.Id;

    var clickEvent = "window.open ('" + href + "', '" + target + "', 'directories=no,width=850,height=650,location=no,menubar=no,resizable=no,scrollbars=no,status=yes,titlebar=no,toolbar=no'); false;";

    formattedCellValue += "<div class=\"ui-widget ui-state-default ui-corner-all\" style=\"display: inline-block; float: left; width: 16px;\"><a href=\"javascript:void(0);\" onclick=\"" + clickEvent + "\">" + iconEdit + "</a></div>";

    formattedCellValue += "<div class=\"ui-widget ui-state-default ui-corner-all\" style=\"display: inline-block; float: left; width: 16px;\"><a href=\"javascript:void(0);\" onclick=\"ContentGrid_OnDelete();\">" + iconDelete + "</a></div>";

    return formattedCellValue;

}

function ContentGrid_Formatter_Action_Sponsor(cellValue, options, rowObject) {

    var formattedCellValue = "";

    var iconEdit = "<span class=\"ui-icon ui-icon-newwin\"></span>";

    // USE THE SELECTED OBJECT TYPE VERSUS THE INCOMING OBJECT TYPE

    // THIS IS TO SUPPORT WHEN ONE OBJECT TYPE IS USED BY SEPARATE CONFIG OPTIONS 

    var href = $("#RootUrl").val() + "Sponsor/Sponsor/" + rowObject.Id;

    var target = rowObject.ObjectType + "_" + rowObject.Id;

    var clickEvent = "window.open ('" + href + "', '" + target + "', 'directories=no,location=no,menubar=no,resizable=yes,status=yes,titlebar=no,toolbar=no'); false;";

    formattedCellValue += "<div class=\"ui-widget ui-state-default ui-corner-all\" style=\"display: inline-block; float: left; width: 16px;\"><a href=\"javascript:void(0);\" onclick=\"" + clickEvent + "\">" + iconEdit + "</a></div>";

    return formattedCellValue;

}

function ContentGrid_Initialize(requestUrl, columnModel) {

    $("#ContentGrid").jqGrid({

        width: 1,

        url: requestUrl,

        datatype: "json",

        rowNum: 50,

        rowList: [10, 25, 50],

        colModel: columnModel,

        jsonReader: { repeatitems: false },

        pager: "#ContentGridPager",

        loadComplete: function (data) { ContentGrid_OnLoadComplete(data); },

        loadError: function (xhr, status, error) { ContentGrid_OnLoadError(xhr, status, error); }

    });

    jqGrid_RemoveCorners("ContentGrid");


    $("#ContentGrid").jqGrid("navGrid", "#ContentGridPager", { edit: false, add: true, del: false, search: false });

    $("#ContentGridPager_left").removeAttr("style");


    // ADD FILTERTOOBAR 

    $("#ContentGrid").jqGrid("filterToolbar", { searchOnEnter: true, stringResult: true });


    // ADD CUSTOM EVENT HANDLERS 

    $("td#add_ContentGrid").unbind("click");

    $("td#add_ContentGrid").click(ContentGrid_OnAdd);

    return;

}

function ContentGrid_Refresh() {

    if ($("#ContentGridPager_left").length > 0) {

        $("#ContentGrid").jqGrid().GridUnload();

    }

    var requestUrl = $("#RootUrl").val() + "" + selectedController + "/" + selectedAction + "?" + selectedParameters;

    ContentGrid_Initialize(requestUrl, ContentGrid_ColumnModels[selectedObjectType]);

    Window_OnResize();

}

function ContentGrid_OnLoadComplete(data) {

    return;

}

function ContentGrid_OnLoadError(xhr, status, error) {

    alert("Error Loading Data from the Server: " + error);

    return;

}

function ContentGrid_OnAdd() {

    var configurationUrl = $("#RootUrl").val() + selectedController + "/" + selectedObjectType + "/0";

    window.open(configurationUrl, "_blank", "directories=no,width=850,height=650,location=no,menubar=no,resizable=no,scrollbars=no,status=yes,titlebar=no,toolbar=no'", false);

    return;

}

function ContentGrid_OnDelete() {

    // PUSH THE DELETE TO ANOTHER THREAD SO THAT THE CLICK EVENT CAN FINISH ITS BUBBLE 

    // THIS ALLOWS THE JQGRID TO SELECT THE ROW 

    setTimeout(function () {

        var selectedRowId = $("#ContentGrid").jqGrid("getGridParam", "selrow");

        var selectedId = $("#ContentGrid").jqGrid("getCell", selectedRowId, "Id");

        var selectedName = $("#ContentGrid").jqGrid("getCell", selectedRowId, "Name");


        if (selectedId) {

            if (confirm("Are you sure you want to delete \"" + selectedName + "\"?")) {

                var postbackUrl = $("#RootUrl").val() + selectedController + "/" + selectedObjectType + "Delete/" + selectedId;

                $.ajax({

                    type: "DELETE",

                    url: postbackUrl,

                    data: [],

                    error: function (jqXHR, textStatus, errorThrown) {

                        alert("Error performing AJAX page request: " + errorThrown + " [Url:" + postbackUrl + "]");

                        LastResponseMessage_SetError(errorThrown);

                    },

                    success: function (response) {

                        if (!response.Result) {

                            alert(response.ExceptionMessage);

                        }

                    },

                    complete: function () {

                        ContentGrid_Refresh();

                    }

                });

            }

        }

    });

}

function SponsorSearch_OnClick() {

    ContentSelection_OnClick(null);

    $("#ContentHeader").show();

    $("#ContentHeader").text("Sponsor Search Results");

    $("#ContentBody").show();


    if ($("#ContentGridPager_left").length > 0) {

        $("#ContentGrid").jqGrid().GridUnload();

    }

    var searchCriteria = escape($("#SearchCriteria").val());

    var searchUrl = $("#RootUrl").val() + "Sponsor/SponsorSearch?Criteria=" + searchCriteria;

    ContentGrid_Initialize(searchUrl, ContentGrid_ColumnModels["Sponsor"]);


    $("td.ContentSelectionContainer").hide();

    $(window).resize();

}

function SponsorAdd_OnClick() {
    
    var sponsorUrl = $("#RootUrl").val() + "Sponsor/Sponsor/0";

    window.open(sponsorUrl, "_blank", "directories=no,width=850,height=650,location=no,menubar=no,resizable=no,scrollbars=no,status=yes,titlebar=no,toolbar=no'", false);
    
}

$(document).ready(function () {

    $(window).resize(Window_OnResize);

    TopLevelSelection_OnClick();


    // DETERMINE IF SEARCH WAS PRESENTED THROUGH THE URL QUERY STRING 

    var searchCriteria = UrlParameterByName("SearchCriteria");
    
    if ((searchCriteria) && (searchCriteria.length > 0)) {

        $("#SearchCriteria").val(searchCriteria);

        setTimeout(function () { $("#SearchButton").click(); }); // SEARCH ON DIFFERENT THREAD

    }


    setTimeout(function () { $(window).resize(); }, 250);

});